<template>
  <div
    class="field-wrapper"
    :class="{
      'field-wrapper-selected': selected,
      'field-wrapper-moving': isMoving
    }"
    :style="{
      display: hidden === 0 ? 'block' : 'none'
    }"
    tabindex="0"
    @keydown="keyDownHandler"
    @contextmenu.stop="onContextMenu"
    @click.stop="selectField(field)"
  >
    <!-- slot是放子组件的内容 -->
    <slot></slot>
    <template v-if="!!designer">
      <div
        v-if="selected"
        class="drag-handler"
        :class="isMoving ? 'drag-handler-moving' : ''"
        :draggable="true"
        @dragstart="onDragStart"
        @dragend="onDragEnd"
        @mousedown.stop="dragMouseDownHandler"
      >
        <!-- 拖拽图标 -->
        <i :title="i18nt('designer.hint.dragHandler')">
          <svg-icon icon-class="el-drag-move" />
        </i>
        <i>
          {{ field.options.name }}
        </i>
        <i v-if="field.options.hidden === true">
          <svg-icon icon-class="el-hide" />
        </i>
      </div>

      <div v-if="designer && designer.showWidgetId" class="field-id-container">
        <span class="field-label">{{ field.options.id }}</span>
      </div>

      <!-- <div v-if="designer && designer.showWidgetData" class="field-data-container">
        <span class="field-data-label">{{ getDataBindingLabel }}</span>
      </div> -->

      <div v-if="designer && designer.showWidgetData" class="field-data-container" 
           :class="{'field-data-center': field.type === 'picture'}">
        <span class="field-data-label">{{ getDataBindingLabel }}</span>
      </div>

      <div
        v-if="selected"
        class="field-widget-resize top-left-resize"
        @mousedown.stop="resizeMousedownHandler('topLeft')"
      ></div>

      <div
        v-if="selected"
        class="field-widget-resize top-right-resize"
        @mousedown.stop="resizeMousedownHandler('topRight')"
      ></div>

      <div
        v-if="selected"
        class="field-widget-resize bottom-left-resize"
        @mousedown.stop="resizeMousedownHandler('bottomLeft')"
      ></div>

      <div
        v-if="selected"
        class="field-widget-resize bottom-right-resize"
        @mousedown.stop="resizeMousedownHandler('bottomRight')"
      ></div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'StaticContentWrapper',
  props: {
    field: Object,
    designer: Object,
    settings: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    scale: {
      type: Number,
      default: 1
    },
    allowSelect: {
      type: Boolean,
      default: true
    },

    designState: {
      type: Boolean,
      default: false
    },

    hidden: {
      type: Number,
      default: 0
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: ''
    }
  },
  data() {
    return {
      isResizing: false,
      resizeType: '',
      isMoving: false,
    }
  },
  computed: {
    selected() {
      if (!this.designer) {
        return false
      }

      if (!this.designer.selectedWidget) {
        return false
      }

      return this.field.id === this.designer.selectedWidget.id
    },
    getDataBindingLabel() {
      if (!this.field.options) return ''
      if (this.field.type=='number' || this.field.type=='slider' ){
      // 检查是否有Modbus地址绑定
      if (this.field.options.type == 'modbus') {
        return `M-${this.field.options.modbusAddress}(${this.field.options.name})`
      }

      // 检查是否有用户自定义地址绑定
      if (this.field.options.type == 'userData') {
        return `U-${this.field.options.userDataId}-${this.field.options.userDataAddress}(${this.field.options.name})`
      }
      return '无绑定'
    }

    if (this.field.type=='staticText' || this.field.type=='button' || this.field.type=='progress' || this.field.type=='qrCode' || this.field.type=='switch' || this.field.type=='gif' || this.field.type=='gif2' || this.field.type=='select' || this.field.type=='module' || this.field.type=='table' || this.field.type=='slidePage' ){
      return `${this.field.options.name}`;
    }

    if (this.field.type=='text' ){
      if (this.field.options.type == 'modbus') {
        return `M-${this.field.options.modbusAddress}-${this.field.options.modbusAddressLen}(${this.field.options.name})`
      }
      if (this.field.options.type == 'userData') {
        return `U-${this.field.options.userDataId}-${this.field.options.userDataAddress}-${this.field.options.userAddressLen}(${this.field.options.name})`
      }
      return '无绑定'
    }

    if (this.field.type=='picture' ){
  if (this.field.options.pngId){
    // 使用split方法分割字符串，取第一部分
    const parts = this.field.options.pngId.split('.');
    return `${parts[0]}(${this.field.options.name})`;  // 只返回文件名部分，不包含扩展名
  }
  return '无绑定'
}

    if (this.field.type=='led' ){
      if (this.field.options.type == 'modbus') {
        return `M-${this.field.options.modbusAddress}-${this.field.options.bit}(${this.field.options.name})`
      }
      if (this.field.options.type == 'userData') {
        return `U-${this.field.options.userDataId}-${this.field.options.userDataAddress}-${this.field.options.bit}(${this.field.options.name})`
      }
      return '无绑定'
    }

    },
    positionX() {
      return this.field.options.x || 0
    },
    scalePositionX() {
      return this.positionX * this.scale
    },
    positionY() {
      return this.field.options.y || 0
    },
    scalePositionY() {
      return this.positionY * this.scale
    },
    width() {
      return this.field.options.width || 'auto'
    },
    scaleWidth() {
      if (this.width === 'auto') {
        return 'auto'
      }
      return this.width * this.scale
    },
    height() {
      if (this.field.options.height) {
        return this.field.options.height
      }

      if (this.field.options.width) {
        return this.field.options.width
      }

      return 'auto'
    },
    scaleHeight() {
      if (this.height === 'auto') {
        return 'auto'
      }
      return this.height * this.scale
    },
    parentWidth() {
      if (this.parentWidget) {
        return this.parentWidget.options.width
      }
      return this.settings.width
    },
    scaleParentWidth() {
      return this.parentWidth * this.scale
    },
    parentHeight() {
      if (this.parentWidget) {
        return this.parentWidget.options.height
      }
      return this.settings.height
    },
    scaleParentHeight() {
      return this.parentHeight * this.scale
    }
  },
  mounted() {
    document.addEventListener('mousemove', this.resizeMousemoveHandler)
    document.addEventListener('mouseup', this.resizeMouseupHandler)
  },
  unmounted() {
    document.removeEventListener('mousemove', this.resizeMousemoveHandler)
    document.removeEventListener('mouseup', this.resizeMouseupHandler)
  },

  methods: {
    onContextMenu(event) {
      event.preventDefault()

      if (
        event.currentTarget.closest('.button-edit-canvas') ||
        event.currentTarget.closest('.module-edit-canvas')
      ) {
        this.designer.setSelected(this.field)
      } else {
        if (!this.parentWidget) {
          this.designer.setSelected(this.field)
        } else {
          this.designer.setSelected(this.parentWidget)
        }
      }

      this.$emitter.emit('showContextMenu', {
        clientX: event.clientX,
        clientY: event.clientY,
        designerId: this.designer.id
      })
    },
    selectField(field) {
      if (this.designer) {
        if (this.allowSelect) {
          this.designer.setSelected(field)
        } else {
          this.designer.setSelected(this.parentWidget)
        }
      }
    },

    onDragStart(evt) {
      evt.dataTransfer.effectAllowed = 'move'

      this.field.offset = {
        x: evt.layerX,
        y: evt.layerY
      }
      this.designer.drag(this.field)
    },
    onDragEnd() {
      console.log(this.parentWidget)
      if (
        this.parentWidget &&
        (this.parentWidget.type === 'button' || this.parentWidget.type === 'module'
        ||this.parentWidget.type === "slidePage")
      ) {
        this.$emitter.emit('widget-drag-end', this.field)
      } else {
        this.$emitter.emit('drag-end', this.field)
      }

      this.resizeMouseupHandler()
    },
    dragMouseDownHandler() {
      this.isMoving = true
    },

    resizeMousedownHandler(type) {
      console.log(type)
      this.isResizing = true
      this.resizeType = type
    },

    resizeMouseupHandler() {
      this.isResizing = false
      this.isMoving = false
      this.resizeType = ''
    },

    resizeMousemoveHandler(e) {
      if (this.isResizing) {
        const { movementX, movementY } = e;
        let scaleX = this.scalePositionX;
        let scaleY = this.scalePositionY;
        let scaleWidth = this.scaleWidth;
        let scaleHeight = this.scaleHeight;
        
        const minWidth = 5;
        const minHeight = 5;
        const maxWidth = this.scaleParentWidth - scaleX;
        const maxHeight = this.scaleParentHeight - scaleY;

        switch (this.resizeType) {
          case 'topLeft':
            scaleX = Math.max(0, Math.min(scaleX + movementX, scaleX + scaleWidth - minWidth));
            scaleWidth = Math.max(minWidth, Math.min(scaleWidth - movementX, scaleX + scaleWidth));
            
            scaleY = Math.max(0, Math.min(scaleY + movementY, scaleY + scaleHeight - minHeight));
            scaleHeight = Math.max(minHeight, Math.min(scaleHeight - movementY, scaleY + scaleHeight));
            break;

          case 'topRight':
            scaleWidth = Math.max(minWidth, Math.min(scaleWidth + movementX, maxWidth));
            scaleY = Math.max(0, Math.min(scaleY + movementY, scaleY + scaleHeight - minHeight));
            scaleHeight = Math.max(minHeight, Math.min(scaleHeight - movementY, scaleY + scaleHeight));
            break;

          case 'bottomLeft':
            scaleX = Math.max(0, Math.min(scaleX + movementX, scaleX + scaleWidth - minWidth));
            scaleWidth = Math.max(minWidth, Math.min(scaleWidth - movementX, scaleX + scaleWidth));
            scaleHeight = Math.max(minHeight, Math.min(scaleHeight + movementY, maxHeight));
            break;

          case 'bottomRight':
            scaleWidth = Math.max(minWidth, Math.min(scaleWidth + movementX, maxWidth));
            scaleHeight = Math.max(minHeight, Math.min(scaleHeight + movementY, maxHeight));
            break;

          default:
            break;
        }

        this.field.options.x = Math.round(scaleX / this.scale);
        this.field.options.y = Math.round(scaleY / this.scale);
        this.field.options.width = Math.round(scaleWidth / this.scale);
        this.field.options.height = Math.round(scaleHeight / this.scale);
      }
    },
    keyDownHandler(event) {
      event.preventDefault()

      switch (event.key) {
        case 'ArrowUp':
          let upY = this.field.options.y - 1
          if (upY < 0) {
            upY = 0
          }
          this.field.options.y = upY
          break
        case 'ArrowDown':
          let downY = this.field.options.y + 1
          if (this.parentWidget) {
            if (downY + this.field.options.height > this.parentWidget.options.height) {
              downY = this.parentWidget.options.height - this.field.options.height
            }
          } else {
            if (downY + this.field.options.height > this.settings.height) {
              downY = this.settings.height - this.field.options.height
            }
          }
          this.field.options.y = downY
          break
        case 'ArrowLeft':
          let leftX = this.field.options.x - 1
          if (leftX < 0) {
            leftX = 0
          }
          this.field.options.x = leftX
          break
        case 'ArrowRight':
          let rightX = this.field.options.x + 1
          if (this.parentWidget) {
            if (rightX + this.field.options.width > this.parentWidget.options.width) {
              rightX = this.parentWidget.options.width - this.field.options.width
            }
          } else {
            if (rightX + this.field.options.width > this.settings.width) {
              rightX = this.settings.width - this.field.options.width
            }
          }
          this.field.options.x = rightX
          break
        case 'Delete':
          this.designer.deleteWidget(this.designer.selectedWidget, this.designer.widgetList)
          break
        default:
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.field-wrapper {
  position: absolute;
  min-height: 20px;
  min-width: 40px;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }

  &.field-wrapper-selected {
    border: 1px solid #0000ff;
  }

  &.field-wrapper-moving {
    border: none;
  }

  .drag-handler {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgba(64, 158, 255, 0.6);
    user-select: none;

    i {
      font-size: 12px;
      font-style: normal;
      color: #fff;
      margin: 4px;
      cursor: move;
    }

    &:hover {
      opacity: 1;
      background: $--color-primary;
    }
  }

  .drag-handler.drag-handler-moving {
    background: #c3c3c3;
  }

  .field-id-container {
    position: absolute;
    top: 2px;
    right: 5px;
    line-height: 20px;
    color: $--color-primary;
  }

  .field-data-container {
    position: absolute;
    top: 0px;
    right: 0px;
    line-height: 20px;
    color: #0000ff85 ;
    //background-color: rgba(255, 255, 255, 0.7);
    padding: 0 4px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: bold;
    z-index: 10;
  
  /* 图片控件的地址信息居中显示 */
    &.field-data-center {
      position: absolute;
      top: 5%;
      left: 50%;
      right: auto;
      color: #0000ff85 ;
      transform: translate(-50%, -50%);
      //background-color: rgba(255, 255, 255, 0.8);
      //border: 1px solid #0000ff85;
      padding: 2px 6px;
    }
  }

  .field-widget-resize {
    position: absolute;
    width: 20px;
    height: 20px;
  }

  .top-left-resize {
    top: 0;
    left: 0;
    cursor: nwse-resize;
  }

  .top-right-resize {
    top: 0;
    right: 0;
    cursor: nesw-resize;
  }

  .bottom-left-resize {
    bottom: 0;
    left: 0;
    cursor: nesw-resize;
  }

  .bottom-right-resize {
    bottom: 0;
    right: 0;
    cursor: nwse-resize;
  }
}
</style>